package com.taplinker.client.im.rpc;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.text.TextUtils;

import com.taplinker.client.im.domain.ImDataCenter;
import com.taplinker.client.im.protocol.CsIcon;
import com.taplinker.client.im.protocol.TapLinkerConversation;
import com.taplinker.client.im.protocol.TapLinkerMessage;
import com.taplinker.client.im.rpc.body.Cmd015Rep;
import com.taplinker.client.im.rpc.body.Cmd015Req;
import com.taplinker.core.rpc.Result;
import com.taplinker.core.util.json.JsonUtil;

public class Cmd015 extends SimpleSocketCommand<Cmd015Req> {

	private TapLinkerConversation conversation = null;
	public Cmd015(int pageIndex,TapLinkerConversation conversation) {
		body = new Cmd015Req();
		body.setConversationId(conversation.getId());
		body.setRecordNo(pageIndex);
		body.setPageSize(ImDataCenter.PAGE_SIZE);
		this.conversation= conversation; 
	}
	
	public Cmd015(int pageIndex,int size,TapLinkerConversation conversation) {
		body = new Cmd015Req();
		body.setConversationId(conversation.getId());
		body.setRecordNo(pageIndex);
		body.setPageSize(size);
		this.conversation= conversation; 
	}
	
	@Override
	public void yes(Result result) {
		super.yes(result);
		Cmd015Rep value = JsonUtil.jsonToObject(((IMMessageResponse) result.object).getMessage().getBody(), Cmd015Rep.class);
		
		List<TapLinkerMessage> messages = value.getMessage();
		Map<Long, CsIcon> csIconMap = new HashMap<Long, CsIcon>();
		List<CsIcon> csicons = value.getCsicons();
		if (csicons != null) {
			for (CsIcon csIcon : csicons) {
				csIconMap.put(csIcon.getUserId(), csIcon);
			}
		}
		for(TapLinkerMessage tapLinkerMessage : messages) {
			long userId = tapLinkerMessage.getSendUserId();
			if (userId > 0 && csIconMap != null && csIconMap.size() > 0) {
				tapLinkerMessage.setSendUser(csIconMap.get(userId).getNickname());
				tapLinkerMessage.setIcon(csIconMap.get(userId).getIcon());
				tapLinkerMessage.setStatus(csIconMap.get(userId).getStatus());
			} else {
				if(TextUtils.isEmpty(conversation.getCustomerName())) {
					tapLinkerMessage.setSendUser(conversation.getVisitor());
				} else {
					tapLinkerMessage.setSendUser(conversation.getCustomerName());
				}
			}
		}
		
		for(TapLinkerMessage item : messages) {
			conversation.getMessages().add(0, item);
		}
		ImDataCenter.getInstance().noticeListener(ImDataCenter.REFRESH_FINISH + conversation.getId());
	}
	
	@Override
	protected String getCommand() {
		return "015";
	}
}
